package com.leyou.item.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.dto.SpecGroupDTO;
import com.leyou.dto.SpecParamDTO;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.mapper.SpecParamMapper;
import com.leyou.item.pojo.SpecGroup;
import com.leyou.item.pojo.SpecParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpecService {

    @Autowired
    private SpecGroupMapper specGroupMapper;
    @Autowired
    private SpecParamMapper specParamMapper;

    //通过cid 查询规格组
    public List<SpecGroupDTO> queryGroupByCategory(Long cid){
        SpecGroup specGroup = new SpecGroup();
        specGroup.setCid(cid);
        List<SpecGroup> specGroups = specGroupMapper.select(specGroup);
        if(CollectionUtils.isEmpty(specGroups)){
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(specGroups,SpecGroupDTO.class);

    }
    //通过gid,cid,searching 查询规格参数
    public List<SpecParamDTO> querySpecParams(Long gid,Long cid,Boolean searching){
        //cid 查的是规格参数页面 gid 查的是搜索页面  searching 是用在搜索页面的参数展示
        if(gid == null && cid == null){
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }

        SpecParam specParam = new SpecParam();
        //设置参数分组的gid
        specParam.setGroupId(gid);
        specParam.setCid(cid);
        specParam.setSearching(searching);
        //select默认的是在创建sql的时候消除 null的字段
        List<SpecParam> specParams = specParamMapper.select(specParam);
        if(CollectionUtils.isEmpty(specParams)){
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }
        return  BeanHelper.copyWithCollection(specParams, SpecParamDTO.class);
    }

    //根据 cid 查询 规格组的信息 其中规格组里面有规格参数
    public List<SpecGroupDTO> findSpecGroupWithParamsBuCid(Long id) {
        List<SpecGroupDTO> list = queryGroupByCategory(id);
        //这里是两个null  在详情页面展示是不需要给 search 参数的
        List<SpecParamDTO> specParamDTOS = querySpecParams(null, id, null);
        Map<Long, List<SpecParamDTO>> map = specParamDTOS.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        list.forEach(specGroupDTO -> {
            specGroupDTO.setParams(map.get(specGroupDTO.getId()));
        });
        return list;
    }
}
